<template>
  <div>
    <SectionTitle title="基础信息" style="margin-bottom: 16px;" />
    <el-form
      ref="baseInfoForm"
      :rules="rules"
      :model="baseInfo"
      :label-position="showMobilePage?'left':'right'"
      class="lineHeight32"
      label-width="90px">
      <el-row class="response-el-row" type="flex">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="申请人" prop="proposerId">
            <selectWithUserLoad
              v-model="baseInfo.proposerObj"
              :default-list="defaultUserList"
              :show-check-user="true"
              value-type="object"
              key-name="id"
              label-name="userName"
              filterable
              placeholder="请选择申请人"
              @change="handleProposerChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="申请部门" prop="departmentId">
            <el-cascader
              v-model="baseInfo.departmentId"
              :show-all-levels="false"
              :options="deptList"
              :props="{
                emitPath:false,
                value: 'id',
                label: 'name',
                checkStrictly: true,
                multiple: false,
              }"
              placeholder="请选择申请部门"
              size="small"
              collapse-tags
              filterable
              clearable>
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                </el-tooltip>
                <span v-else>{{ data.name || '--' }}</span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="所属公司" prop="company">
            <el-select v-model="baseInfo.company" popper-class="global-select-down panel-auto-width">
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.name"
                :value="item.name" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="报销类型" prop="type">
            <el-select v-model="baseInfo.type" popper-class="global-select-down" @change="reimbursementTypeChange">
              <el-option
                v-for="item in reimbursementTypes"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="分摊费用" prop="isAllocation">
            <el-radio-group v-model="baseInfo.isAllocation">
              <el-radio :label="1"><span style="font-size:14px;">是</span></el-radio>
              <el-radio :label="0"><span style="font-size:14px;">否</span></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="冲抵借款" prop="isWriteOff">
            <el-radio-group v-model="baseInfo.isWriteOff" @change="writeOffStatusChange">
              <el-radio :label="1"><span style="font-size:14px;">是</span></el-radio>
              <el-radio :label="0"><span style="font-size:14px;">否</span></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <template v-if="baseInfo.isWriteOff === 1">
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="借款欠额(元)" prop="arrearsAmount">
              <div class="flex-center">
                <el-input v-model="baseInfo.arrearsAmount" disabled prop="arrearsAmount" placeholder="--" />
                <el-tooltip placement="top">
                  <div slot="content">{{ arrearsAmountTip }}</div>
                  <tipIcon is-diy class="ml5"/>
                </el-tooltip>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="冲抵借款欠额(元)" prop="writeOffAmount">
              <el-input
                v-model="baseInfo.writeOffAmount"
                placeholder="请输入"
                type="text"
                maxlength="15"
                oninput="if(value>999999999)value=999999999"
                @input="numInputChange($event, 'writeOffAmount')"/>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
          <el-form-item label="实付金额(元)" prop="paymentAmount">
            <div class="flex-center">
              <el-input v-model="baseInfo.paymentAmount" disabled prop="paymentAmount" placeholder="=总报销金额-冲抵借款欠额" />
              <el-tooltip placement="top">
                <div slot="content">{{ paymentAmountTip }}</div>
                <tipIcon is-diy class="ml5"/>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="附件" prop="attachment">
            <upAttachment
              ref="uploadAttachment"
              :hide-confirm="true"
              :file-list="baseInfo.attachment"
              import-api="/common/file/upload"
              btn-text="上传文件"
              @complateSetData="completeSetData($event, 'attachment')"
              @removeFileList="removeFileList($event, 'attachment')" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import { getIssueOurTitleList } from '@/api/issueInvoice';
import { getDepartmentAll } from '@/api/config';
import { getUserArrears } from '@/api/reimbursement';
import upAttachment from '@/components/Common/upAttachment/index';
import SectionTitle from '@/components/Title';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { mapState } from 'vuex';
export default {
  components: {
    upAttachment,
    selectWithUserLoad,
    SectionTitle
  },
  model: {
    prop: 'baseInfo',
    event: 'change'
  },
  props: {
    baseInfo: {
      type: Object,
      default: () => ({})
    },
    totalAmount: {
      type: Number | String,
      default: null
    }
  },
  data() {
    return {
      deptList: [],
      companyList: [], // 所属公司
      rules: {
        'proposerId': [{ required: true, message: '请选择申请人', trigger: 'change' }],
        'departmentId': [{ required: true, message: '请选择申请部门', trigger: 'change' }],
        'company': [{ required: true, message: '请选择所属公司', trigger: 'change' }],
        'type': [{ required: true, message: '请选择报销类型', trigger: 'change' }],
        'isAllocation': [{ required: true, message: '请选择', trigger: 'change' }],
        'isWriteOff': [{ required: true, message: '请选择', trigger: 'change' }],
        'writeOffAmount': [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    arrearsAmountTip() {
      return '借款欠额=借款金额-还款金额-冲抵借款欠额-转交欠款+被转交欠款';
    },
    paymentAmountTip() {
      return '实付金额=总报销金额-冲抵借款欠额';
    },
    reimbursementTypes() {
      return [
        { id: 0, name: '常规' },
        { id: 1, name: '差旅' }
      ];
    },
    defaultUserList() {
      const { proposerId, proposer, avatar } = this.baseInfo;
      return proposerId && proposer ? [{ id: proposerId, userName: proposer, avatar }] : [];
    }
  },
  watch: {
    'baseInfo.isWriteOff': {
      handler(val) {
        // 勾选'冲抵借款'时，字段动态变化
        this.resetValidRules(val);
        val && this.setArrearsAmount();
      },
      immediate: true
    },
    'baseInfo.proposerId': {
      handler() {
        // 借款欠额对应申请人
        this.setArrearsAmount();
      },
      immediate: true
    },
    'baseInfo.writeOffAmount'(val) {
      // 最大可输入值要小于中报销金额和借款欠额
      // const inputMaxNum = Math.min(+this.totalAmount || 0, +this.baseInfo.arrearsAmount || 0);
      // const currNum = val ? Number(val) : 0;
      // if (currNum > inputMaxNum) {
      //   this.baseInfo.writeOffAmount = inputMaxNum.toFixed(2);
      // }
      this.calculatePaymentAmount();
    },
    totalAmount() {
      this.calculatePaymentAmount();
    }
  },
  created() {
    this.getDeptList();
    this.setDefaultProposer();
    this.queryCompanyList();
  },
  methods: {
    // 获取部门
    getDeptList() {
      getDepartmentAll().then(res => {
        this.deptList = (res && res.data) || [];
      });
    },
    // 获取借款欠额
    setArrearsAmount() {
      if (!this.baseInfo.isWriteOff) return;
      const { proposerId } = this.baseInfo;
      if (!proposerId) {
        this.baseInfo.arrearsAmount = null;
        return;
      }
      getUserArrears(proposerId).then(res => {
        if (res.code === 200) {
          this.baseInfo.arrearsAmount = res.data.amount;
        } else {
          this.baseInfo.arrearsAmount = null;
        }
      }).catch(() => {
        this.baseInfo.arrearsAmount = null;
      });
    },
    writeOffStatusChange() {
      this.baseInfo.writeOffAmount = null;
    },
    reimbursementTypeChange() {
      this.$emit('typeChange');
    },
    resetValidRules(val) {
      const dynamicAttrs = ['writeOffAmount'];
      dynamicAttrs.forEach(key => {
        const currRule = this.rules[key] || [{}];
        currRule[0].required = !!val;
      });
    },
    // 计算实付金额 = 总报销金额-冲抵借款欠额
    calculatePaymentAmount() {
      const writeOffAmount = this.baseInfo.writeOffAmount || 0;
      const totalAmount = this.totalAmount || 0;
      this.baseInfo.paymentAmount = ((+totalAmount) - (+writeOffAmount)).toFixed(2);
    },
    // 提供给父组件来验证完整性
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs['baseInfoForm'].validate().then(() => {
          resolve();
        }).catch(() => {
          reject();
        });
      });
    },
    // 所属公司，数据：通用设置→发票管理→我方抬头数据
    queryCompanyList() {
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          this.companyList = res.data || [];
        }
      });
    },
    handleProposerChange(data) {
      if (!data) return;
      this.baseInfo.proposerId = data.id;
      this.baseInfo.proposer = data.userName;
      this.baseInfo.avatar = data.avatar;
      this.$emit('change', this.baseInfo);
    },
    completeSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.baseInfo[key]) {
        this.baseInfo[key].push(fileList);
      } else {
        this.$set(this.baseInfo, key, [fileList]);
      }
      key === 'certificateFile' && this.$refs['baseInfoForm'].validateField(key);
    },
    removeFileList({ file, index }, key) {
      this.baseInfo[key].splice(index, 1);
      key === 'certificateFile' && this.$refs['baseInfoForm'].validateField(key);
    },
    setDefaultProposer() {
      this.baseInfo.proposerId = this.userInfo.id;
      this.baseInfo.proposer = this.userInfo.userName;
      this.baseInfo.avatar = this.userInfo.avatar;
      this.baseInfo.proposerObj = {
        id: this.baseInfo.proposerId,
        userName: this.baseInfo.proposer,
        avatar: this.baseInfo.avatar
      };
      if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
        const departmentId = this.getFirstDepartment(this.userInfo.departmentAry);
        this.baseInfo.departmentId = departmentId;
      }
    },
    // 获取用户第一个部门的第一个子级部门
    getFirstDepartment(list) {
      if (Array.isArray(list) && list.length) {
        const deptIdArr = list[0].id;
        if (Array.isArray(deptIdArr) && deptIdArr.length) {
          return deptIdArr[deptIdArr.length - 1];
        } else {
          return null;
        }
      } else {
        return null;
      }
    },
    numInputChange(text, prop) {
      let str = text.replace(/[^\d.]/g, ''); // 只允许数字
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后3位
      this.baseInfo[prop] = str;
    },
    // 用于手动触发表单验证
    triggerFormValidate() {
      this.$refs['baseInfoForm'].validate();
    }
  }
};
</script>
<style lang="scss" scoped>
.response-el-row {
  & ::v-deep {
    .el-input__inner {
      height: 32px;
      line-height: 32px;
      width: 240px;
    }
    .el-form-item__content {
      width: 240px;
    }
    .el-input__icon {
      line-height: 32px;
    }
    .el-form-item {
      margin-bottom: 24px;
    }
    .el-select {
      .el-input {
        .el-select__caret {
          color: #333333;
        }
      }
    }
  }
  .indentation-form-item {
    ::v-deep .el-form-item {
      label {
        line-height: 1.2 !important;
      }
    }
  }
}
</style>
